package com.letoken.platform.app.job;

import com.letoken.platform.pub.enums.LetokenTokenTypeEnum;
import com.letoken.platform.pub.enums.TokenTransactionStatusEnum;
import com.letoken.platform.pub.enums.TokenTransactionTypeEnum;
import com.letoken.platform.repo.app.dao.AppUserAssetsHistoryMapper;
import com.letoken.platform.repo.app.dao.AppUserWalletMapper;
import com.letoken.platform.repo.app.po.AppUserAssetsHistory;
import com.letoken.platform.repo.app.po.AppUserWallet;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.web3j.abi.datatypes.Int;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class LPDividendJob {

    @Resource
    private AppUserWalletMapper appUserWalletMapper;

    @Autowired
    AppUserAssetsHistoryMapper appUserAssetsHistoryMapper;

    @XxlJob("LPDividend")
    public  void LPDividend() {
       List<AppUserWallet> walletList = appUserWalletMapper.getLPAmount();
        for (AppUserWallet appUserWallet:walletList) {
            try {
                BigDecimal money = appUserWallet.getAvailableBalance().multiply(new BigDecimal("0.00241"));
                Integer walletId = appUserWalletMapper.checkoutTokenIdAndUserId(LetokenTokenTypeEnum.CAP.getId(), appUserWallet.getUserId());
                AppUserWallet w = appUserWalletMapper.selectForUpdate(walletId);
                AppUserWallet updateW = new AppUserWallet();
                updateW.setId(w.getId());
                updateW.setAvailableBalance(w.getAvailableBalance().add(money));
                appUserWalletMapper.updateById(updateW);

                AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
                assetHistory.setUserId(appUserWallet.getUserId());
                assetHistory.setType(TokenTransactionTypeEnum.LP_Dividend.getValue());
                assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
                assetHistory.setTokenId(LetokenTokenTypeEnum.CAP.getId());
                assetHistory.setAmount(money);
                assetHistory.setBalance(updateW.getAvailableBalance());
                assetHistory.setCreateTime(LocalDateTime.now());
                assetHistory.setUpdateTime(assetHistory.getCreateTime());
                appUserAssetsHistoryMapper.insert(assetHistory);
            }catch (Exception e){
                log.info("LP分红失败,用户id{}",appUserWallet.getUserId());
            }

        }
    }
}
